// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

const TcbRouter = require('tcb-router')

const db = cloud.database()

const signUpCollection = db.collection('signUp')
const MAX_LIMIT = 100

 
// 云函数入口函数
exports.main = async (event, context) => {
  const app = new TcbRouter({
    event
  })

  const wxContext = cloud.getWXContext()
  // app.router('getListByOpenid', async (ctx, next) => {
  //   ctx.body = await db.collection('signUp').where({
  //     _openid: wxContext.OPENID
  //   }).skip(event.start).limit(event.count).orderBy('createTime', 'desc').get().then((res) => {
  //     return res.data
  //   })
  // })
  app.router('activelist', async (ctx, next) => {
    ctx.body = await cloud.database()
      .collection('signUp')
      .skip(event.start)
      .limit(event.count)
      .orderBy('createTime', 'desc')
      .get()
      .then((res) => {
        return res
      })
  })


  app.router('list', async (ctx, next) => {
    const keyword = event.keyword
    let w = {_openid: wxContext.OPENID}
    if (keyword.trim() != '') {
      w = {
        _openid: wxContext.OPENID,
        title: new db.RegExp({
          regexp: keyword,
          options: 'i'
        })
      }
    }

    let signUpList = await signUpCollection.where(w).skip(event.start).limit(event.count)
      .orderBy('createTime', 'desc').get().then((res) => {
        return res.data
      })
    ctx.body = signUpList
  })


  app.router('detail', async (ctx, next) => {
    let activityId = event.activityId
    let detail = await signUpCollection.where({
      _id: activityId
    }).get().then((res) => {
      return res.data
    })

    const countResult = await signUpCollection.count()
    const total = countResult.total
    let peopleList = {
      data: []
    }
    if (total > 0) {
      const batchTimes = Math.ceil(total / MAX_LIMIT)
      const tasks = []
      for (let i = 0; i < batchTimes; i++) {
        let promise = db.collection('signUp-user').skip(i * MAX_LIMIT)
          .limit(MAX_LIMIT).where({
            activityId
          }).orderBy('createTime', 'desc').get()
        tasks.push(promise)
      }
      if (tasks.length > 0) {
        peopleList = (await Promise.all(tasks)).reduce((acc, cur) => {
          return {
            data: acc.data.concat(cur.data)
          }
        })
      }


    }
    ctx.body = {
      peopleList,
      detail
    }
  })

  // app.router('getOwn', async (ctx, next) => {
  //   let ownList = await db.collection('signUp-user').where({
  //     _openid: wxContext.OPENID
  //   }).skip(event.start).limit(event.count).orderBy('createTime', 'desc').get().then((res) => {
  //     return res.data
  //   })

  //   ctx.body=ownList
  // })

  app.router('getOwn', async (ctx, next) => {
    let ownList = await db.collection('signUp-user').aggregate()
      .lookup({
        from: 'signUp',
        localField: 'activityId',
        foreignField: '_id',
        as: 'ownList',
      })
      .end()

    ctx.body = ownList
  })

  app.router('onDel', async (ctx, next) => {
    let acId = event.activeId
    try {
      return await db.collection('signUp').where({
          _openid: wxContext.OPENID,
          _id: acId
        }).remove()
    }
    catch (e) {
      console.error(e)}
  })

  app.router('delUser', async (ctx, next) => {
    let acId = event.activeId
    try {
      return await db.collection('signUp-user').where({
        _openid: wxContext.OPENID,
        activityId: acId
      }).remove()
    }
    catch (e) {
      console.error(e)
    }
  })

  return app.serve()

}